package com.sprouting.ops.utils;

import cn.hutool.core.collection.CollUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 数据校验工具类
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2023/7/6 15:15
 */
public class ValidatorTool {

    /**
     * 验证器
     */
    private final static Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 注解手动触发验证
     * @param obj 被验证对象
     * @return
     * @param <T>
     */
    public static <T> Map<String,StringBuffer> validate(T obj, Class<? extends Default> defaultClass){
        Map<String, StringBuffer> errorMap = null;
        Set<ConstraintViolation<T>> set = VALIDATOR.validate(obj, defaultClass);
        if(set != null && set.size() >0 ){
            errorMap = new HashMap<String,StringBuffer>();
            String property = null;
            for(ConstraintViolation<T> cv : set){
                //这里循环获取错误信息，可以自定义格式
                property = cv.getPropertyPath().toString();
                if(errorMap.get(property) != null){
                    errorMap.get(property).append("," + cv.getMessage());
                }else{
                    StringBuffer sb = new StringBuffer();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }
        return errorMap;
    }

    /**
     * 手动触发数据验证
     * @param obj 被验证对象
     * @param defaultClass 验证对象触发的组
     * @return 错误信息,null即无错误
     * @param <T>
     */
    public static <T> String check(T obj, Class<? extends Default> defaultClass){
        if (obj == null){
            return null;
        }
        if (defaultClass == null){
            defaultClass =  Default.class;
        }

        Set<ConstraintViolation<T>> set = VALIDATOR.validate(obj, defaultClass);
        if (CollUtil.isEmpty(set)){
            return null;
        }
        List<String> collect = set.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
        return collect.toString();
    }

}
